import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, message, Row, Spin } from 'antd';
import {
  WeaNewScroll,
  WeaLocaleProvider,
  WeaMoreButton,
  WeaDialog,
  WeaSearchGroup,
  WeaRichText,
  WeaUpload,
  WeaSelect,
  WeaInput,
} from 'ecCom';
import { RenderForm } from '../util';
import { transfStr } from '../../../util';

const getLabel = WeaLocaleProvider.getLabel;
const MAILPAGENAME = 'SIGNEDIT';
const limitLength = () => ({
  name: {
    length: 25,
    name: getLabel('25034', '姓名'),
    tip: `${getLabel('508503', '输入请限制在')}30 ${getLabel(
      '508504',
      '个文字之内',
    )}`, // 100
  },
  email: {
    length: 30,
    name: getLabel('20869', '邮箱'),
    tip: getLabel('513202', '请输入30位以内的有效邮箱地址'), // 50
    reg: [
      /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
    ],
  },
  jobtitle: {
    length: 30,
    name: getLabel('6086', '岗位'),
    tip: getLabel('513205', '请输入30个字以内的有效岗位信息'), // 50
  },
  location: {
    length: 160,
    name: getLabel('83578', '地址'),
    tip: getLabel('513206', '请输入60字以内的有效地址信息'), // 200
  },
  telephone: {
    length: 18,
    name: getLabel('421', '电话'),
    tip: getLabel('513207', '请输入18位以内的有效电话号码'), // 20
    reg_remarks: [/^\d{3}-\d{7,8}|\d{4}-\d{7,8}$/],
  },
  fax: {
    length: 20,
    name: getLabel('494', '传真'),
    tip: getLabel('513208', '请输入20位以内的有效传真号码'), // 20
    reg_remarks: [
      /(^(\d{2,4}[-_－—]?)?\d{3,8}([-_－—]?\d{3,8})?([-_－—]?\d{1,7})?$)|(^0?1[35]\d{9}$)/,
    ],
  },
  jobname: {
    length: 120,
    name: getLabel('1851', '公司'),
    tip: `${getLabel('508503', '输入请限制在')}100 ${getLabel(
      '508504',
      '个文字之内',
    )}`, // 100
  },
  url: {
    length: 50,
    name: getLabel('20637', '网址'),
    tip: getLabel('513209', '请输入50个字以内的有效网址'), // 50
    reg: [
      /^((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$/,
      /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:\/~+#]*[\w\-@?^=%&\/~+#])?$/,
    ],
  },
  mobile: {
    length: 20,
    name: getLabel('125238', '手机号'),
    tip: getLabel('513210', '请输入20位以内的有效手机号码'), // 50
  },
  selected: {
    length: 15,
    tip: `${getLabel('508503', '输入请限制在')}50 ${getLabel(
      '508504',
      '个文字之内',
    )}`, // 50
  },
});

@inject('settingStore')
@observer
class Edit extends Component {
  constructor(props) {
    super(props);
    this.prefixCls = 'email-setting-sign-edit';
  }

  getInstance = (ref) => {
    if (!this.editRichText) {
      this.editRichText = ref;
    }
  };

  handleStatusChange = (status) => {
    if (status === 'ready') {
      this.richInstanceReady = true;
      this.editRichText.focus('first');
    }
  };

  formChange = (data) => {
    const {
      settingStore: { signStore },
    } = this.props;
    const { setStoreState, createQRcode } = signStore;
    if (Object.prototype.hasOwnProperty.call(data, 'signType')) {
      setStoreState({ signType: data.signType.value * 1 });
      if (data.signType.value * 1) {
        createQRcode();
      }
    }
  };

  getForm = (form, fields) => {
    const { isFormInit } = form;
    let group = [];
    isFormInit &&
      fields &&
      fields.map((c) => {
        let items = [];
        c.items.map((field) => {
          items.push({
            com: RenderForm(form, field, '', '', { onChange: this.formChange }),
          });
        });
        group.push(
          <WeaSearchGroup
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaSearchGroup@majamm@${MAILPAGENAME}form`}
            col={1}
            title={c.title}
            needTigger={true}
            showGroup={c.defaultshow}
            items={items}
          />,
        );
      });
    return group;
  };

  getFormContent = (editRichValue, signType) => (
    <WeaSearchGroup
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaSearchGroup@tjka9r`}
      needTigger
      showGroup
      title={getLabel(384453, '签名内容')}
      style={{ display: !signType ? 'block' : 'none' }}
    >
      {' '}
      {/* 富文本报错问题 */}
      <div className={`${this.prefixCls}-formcontent`}>
        <WeaRichText
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRichText@c8bdff`}
          ref={this.getInstance}
          value={editRichValue}
          ckConfig={{
            toolbar: [
              { name: 'document', items: ['Source'] },
              {
                name: 'paragraph',
                items: [
                  'JustifyLeft',
                  'JustifyCenter',
                  'JustifyRight',
                  '-',
                  'NumberedList',
                  'BulletedList',
                ],
              },
              { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
              { name: 'colors', items: ['TextColor'] },
              {
                name: 'basicstyles',
                items: ['Bold', 'Italic', 'Underline', 'Strike'],
              },
              { name: 'insert', items: ['Image', 'Table', 'Smiley'] },
            ],
            height: 260,
            uploadUrl: '/api/blog/fileupload/uploadimage',
          }}
          onStatusChange={this.handleStatusChange}
          onToolsChange={transfStr}
        />
      </div>
    </WeaSearchGroup>
  );

  editElectItem = (data) => {
    const {
      settingStore: { signStore },
    } = this.props;
    const { electOptions, setStoreState } = signStore;
    let newOptions = toJS(electOptions).map((v) => {
      // promise only one option in edit state
      let newOption = { ...v };
      if (newOption.id === data.id && !newOption.isEdit) {
        return { ...newOption, isEdit: true };
      } else if (newOption.id !== data.id && newOption.isEdit) {
        return { ...newOption, isEdit: false };
      }
      return newOption;
    });
    setStoreState({ electOptions: newOptions, electEditKey: data.key });
  };

  userInfo = (e) => {
    const {
      settingStore: { signStore },
    } = this.props;
    const { setStoreState, electOptions } = signStore;
    let target = e.target;
    if (target.className === 'elect-item') {
      let tempOptions = toJS(electOptions).map(item => ({
        ...item,
        isEdit: false,
      }));
      setStoreState({ electOptions: tempOptions });
    }
  };

  electItemRender = (data, electInfo) => {
    const {
      settingStore: { signStore },
    } = this.props;
    const {
      addElectItem,
      electOtherOptions,
      deleteElectItem,
      electInfoChange,
      electInfoOnBlur,
      electEditKey,
      electSelectChange,
      setStoreState,
      innStorage,
    } = signStore;
    let electKey = electEditKey === '' ? data.key : electEditKey;
    return (
      <Row
        ecId={`${(this && this.props && this.props.ecId) || ''}_Row@n74sj0`}
        className="elect-item"
        key={data.id}
      >
        {data.isEdit && data.deletable
          ? [
              <WeaSelect
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaSelect@r7dxvs@${MAILPAGENAME}${electKey}`}
                value={electKey}
                options={[data, ...electOtherOptions]}
                onChange={e => electSelectChange(e, data)}
              />,
              <WeaInput
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaInput@suh8fn@${MAILPAGENAME}${electKey}`}
                value={toJS(electInfo)[electKey] || ''}
                onChange={v => electInfoChange(electKey, v)}
                onBlur={value =>
                  electInfoOnBlur(value, electKey, limitLength()[electKey])
                }
                stringLength={limitLength()[electKey].length}
                helpfulTip={limitLength()[electKey].tip}
                onFocus={(v) => {
                  setStoreState({
                    innStorage: {
                      ...innStorage,
                      [electKey]: v || toJS(electInfo)[electKey],
                    },
                  });
                }}
              />,
            ]
          : data.isEdit && !data.deletable
          ? [
              <span className="show-name">{data.showname}:</span>,
              <WeaInput
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaInput@6r48q6@${MAILPAGENAME}${data.key}`}
                value={toJS(electInfo)[data.key] || ''}
                onChange={v => electInfoChange(data.key, v)}
                onBlur={value =>
                  electInfoOnBlur(value, data.key, limitLength()[data.key])
                }
                stringLength={limitLength()[data.key].length}
                helpfulTip={limitLength()[data.key].tip}
                onFocus={(v) => {
                  setStoreState({
                    innStorage: { ...innStorage, [data.key]: v },
                  });
                }}
              />,
            ]
          : [
              <div className="name">
                {data.showname}: &nbsp;&nbsp;{toJS(electInfo)[data.key] || ''}
              </div>,
              <div className="option">
                <i className="icon-coms-Add-to" onClick={addElectItem} />
                <i
                  className="icon-coms-edit"
                  onClick={() => this.editElectItem(data)}
                />
                {data.deletable && (
                  <i
                    className="icon-coms-delete"
                    onClick={() => deleteElectItem(data)}
                  />
                )}
              </div>,
            ]}
        <div className="clear" />
      </Row>
    );
  };

  getElectContent = (electOptions, electImg, electInfo, signType) => {
    const electCls = `${this.prefixCls}-elect`;
    const {
      settingStore: { signStore },
    } = this.props;
    const { qrCode, setStoreState, createQRcode } = signStore;
    return (
      <WeaSearchGroup
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaSearchGroup@t3xguv`}
        needTigger
        showGroup
        title={getLabel(384453, '签名内容')}
        style={{ display: signType ? 'block' : 'none' }}
      >
        <div className={electCls}>
          <div className={`${electCls}-user`}>
            <div className={`${electCls}-user-img`}>
              <img src={electImg.imgSrc || ''} alt="" />
              <WeaUpload
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaUpload@y6q2ug`}
                datas={[toJS(electImg)]}
                uploadUrl="/api/email/setting/uploadOperate"
                category="string"
                multiSelection={false}
                maxFilesNumber={1}
                limitType={'jpg,gif,png'}
                onChange={(ids, list) => {
                  setStoreState({ electDefaultImg: list[0] });
                }}
              >
                <div className="change-img">
                  <p>{getLabel(384454, '更换照片')}</p>
                  <p>{getLabel(384455, '建议尺寸')}(400*600)</p>
                </div>
              </WeaUpload>
            </div>
            <div className={`${electCls}-user-info`} onClick={this.userInfo}>
              <WeaNewScroll
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaNewScroll@2dyhc1`}
                height={243}
              >
                {toJS(electOptions).map(item =>
                  this.electItemRender(item, electInfo),
                )}
              </WeaNewScroll>
            </div>
          </div>
          <div className={`${electCls}-qrcode`}>
            <div className={`${electCls}-qrcode-container`}>
              <p className={`${electCls}-qrcode-refresh`}>
                <i className="icon-coms-Refresh" onClick={createQRcode} />
              </p>
              <div className={`${electCls}-qrcode-img`}>
                <img src={qrCode || ''} alt="" />
              </div>
              <p className={`${electCls}-qrcode-info`}>
                {getLabel(83074, '扫描该二维码，可以将电子名片保存到手机')}
              </p>
            </div>
          </div>
        </div>
      </WeaSearchGroup>
    );
  };

  /* 新建弹窗打开 */
  newSign = (params = {}, callback) => {
    const {
      settingStore: { signStore },
    } = this.props;
    const { getEmailSignCondition, setStoreState } = signStore;
    getEmailSignCondition({ type: 'add', ...params }, () => {
      setStoreState({
        editTitle: getLabel(384378, '新建签名'),
        editType: 'new',
      });
      if (callback && typeof callback === 'function') callback();
    });
  };

  onSubmit = () => {
    const {
      settingStore: { signStore },
      onSubmit,
    } = this.props;
    const {
      operateUserMailSign,
      editForm,
      signType,
      electInfo,
      electDefaultImg,
      editType,
      editId,
      electOptions,
    } = signStore;
    const formParam = editForm.getFormParams() || {};
    if (this.richInstanceReady && !this.editRichText.checkMode()) {
      message.error(
        getLabel(
          '384536',
          '不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式',
        ),
      );
      return;
    }
    if (formParam.signType === '1') {
      // 校验
      let infoArr = Object.keys(toJS(electInfo));
      for (let i = 0; i < infoArr.length; i++) {
        let item = infoArr[i];
        let value = toJS(electInfo)[item];
        if (
          limitLength()[item] &&
          limitLength()[item].reg &&
          limitLength()[item].name
        ) {
          let tempArr = limitLength()[item].reg.filter(v => v.test(value));
          if (value && tempArr.length == 0) {
            message.error(
              getLabel('520146', '请输入正确的{name}格式信息').replace(
                '{name}',
                limitLength()[item].name,
              ),
            );
            return;
          }
        }
        if (
          limitLength()[item] &&
          limitLength()[item].length &&
          limitLength()[item].name
        ) {
          if (value.length > limitLength()[item].length) {
            message.error(
              getLabel('520147', '请输入正确的{name}长度信息').replace(
                '{name}',
                limitLength()[item].name,
              ),
            );
            return;
          }
        }
      }
    }

    let params = { ...formParam, operation: 'add' };
    let selected = toJS(electOptions)
      .map(option => `${option.id}`)
      .join();
    let signContent =
      (this.richInstanceReady &&
        this.editRichText &&
        this.editRichText.getData()) ||
      '';
    params = !signType
      ? { ...params, signContent }
      : {
          ...params,
          ...toJS(electInfo),
          fileid: electDefaultImg.fileid,
          filename: electDefaultImg.filename,
          signheadpath: electDefaultImg.imgSrc
            .replace('data:image/png;base64,', '')
            .replace(/[\n|\r]/gi, ''),
          selected,
        };
    params =
      editType === 'edit'
        ? { ...params, id: editId, operation: 'update' }
        : params;
    operateUserMailSign(params).then((res) => {
      if (res.flag) {
        message.success(getLabel(83551, '保存成功！'));
        this.onCancel();
      } else {
        let errorMsg =
          res.message === 'repeat'
            ? getLabel('26603', '名称重复')
            : getLabel(21809, '保存失败，请重试！');
        message.error(errorMsg);
      }
      if (onSubmit && typeof onSubmit === 'function') onSubmit(res);
    });
  };

  onCancel = () => {
    const {
      settingStore: { signStore },
      onCancel,
    } = this.props;
    const { editForm, setStoreState } = signStore;
    setStoreState({
      editRichValue: '',
      editTitle: '',
      editId: '',
      editType: '',
      electOptions: [],
      electDefaultImg: {},
      electOtherOptions: [],
      qrCode: '',
      electSelected: [],
    });
    this.editRichText = null;
    this.richInstanceReady = false;
    editForm.resetForm();
    if (onCancel && typeof onCancel === 'function') onCancel();
  };

  onSave = () => {
    const {
      settingStore: { signStore },
    } = this.props;
    signStore.onEditSubmit(this.onSubmit);
  };

  render() {
    const {
      settingStore: { signStore },
      visible,
    } = this.props;
    const {
      editTitle,
      editForm,
      editFields,
      editRichValue,
      signType,
      electOptions,
      electDefaultImg,
      electInfo,
      editLoading,
    } = signStore;
    const buttons = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@i3nj9k@${MAILPAGENAME}onsave`}
        type="primary"
        onClick={this.onSave}
      >
        {getLabel(30986, '保存')}
      </Button>,
      <WeaMoreButton
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaMoreButton@m7kxqb@${MAILPAGENAME}more`}
      />,
    ];
    return (
      <WeaDialog
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaDialog@o4d4sq`}
        icon="icon-coms-email"
        iconBgcolor="#a0b0ba"
        title={editTitle}
        style={{ width: 787, height: 500 }}
        className={this.prefixCls}
        visible={visible}
        onCancel={this.onCancel}
        buttons={buttons}
        hasScroll
      >
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@ojxgl9`}
          spinning={editLoading}
        >
          {this.getForm(editForm, editFields)}
          {this.getElectContent(
            electOptions,
            electDefaultImg,
            electInfo,
            signType,
          )}
          {this.getFormContent(editRichValue, signType)}
        </Spin>
      </WeaDialog>
    );
  }
}

/*
  外部调用方式：
  visible: must 控制弹窗显隐
  onHandleAdd: 点击添加联系人执行方法
  onCancel: 取消/关闭弹窗回调
  onSubmit: 保存回调
  open方法： 通过ref调用newSign(params, callback)
*/

export default Edit;
